/**
 * Created by Administrator on 2016/7/1.
 */
import React from 'react'
import {bindActionCreators} from 'redux'
import {Link} from 'react-router-dom'
import {connect} from 'react-redux'
import PropTypes from 'prop-types'
import {NavBar, Carousel, Drawer, ListView, Icon} from 'antd-mobile'
import {getHomeList, getThemes, getTheme, getHomeNewsMore} from '../actions/home'
import {HomeList} from "../components/HomeList"
import {Sidebar} from "../components/Sidebar"
import {agentImageURL, formatWeekDate} from '../utils'

import '../assets/less/home.less'

const mapStateToProps = state => (
    {
        home: state.home
    }
)

const mapDispatchTpProps = dispatch => bindActionCreators({
    getHomeList,
    getThemes,
    getTheme,
    getHomeNewsMore
}, dispatch)

/**
 * connect中间件
 * connect一定要写在需要传递参数的组件头部，因为这是语法规则，只对当前关联的组件生效，和java的原理是一致的
 * state用法：state => state（传递全部state）
 * dispatch用法：（单个action）bindActionCreators(navActions, dispatch)，（多个action）bindActionCreators({...action1, ...action2}, dispatch)
 */
class HomeContainer extends React.Component {
    constructor(props) {
        super(props);
        //构造函数用法
        //常用来绑定自定义函数，切记不要在这里或者组件的任何位置setState，state全部在reducer初始化，相信对开发的后期很有帮助
        //例子：this.myfunction = this.myfunction.bind(this)
        // this.handleClick = this.handleClick.bind(this)
        const dataSource = new ListView.DataSource({
            rowHasChanged: (row1, row2) => row1 !== row2,
        });
        this.state = {
            dataSource: dataSource.cloneWithRows({}),
            isLoading: false,
            open: false,
            storiesList: []
        }
        this.onOpenChange = this.onOpenChange.bind(this)
        this.onEndReached = this.onEndReached.bind(this)
    }

    onOpenChange = () => {
        this.setState({open: !this.state.open});
    }

    async componentDidMount() {
        const {top_stories, stories} = this.props.home.homeList
        if (stories || !stories.length || !top_stories || !top_stories.length) {
            await this.props.getHomeList();
        }
        await this.props.getThemes()

    }

    onEndReached = async (event) => {
        // load new data
        // hasMore: from backend data, indicates whether it is the last page, here is false
        // if (this.state.isLoading && !this.state.hasMore) {
        //     return;
        // }
        console.log('reach end', event);
        this.setState({isLoading: true});
        await this.props.getHomeNewsMore(this.props.home.homeDate)
        let data = [...this.state.storiesList, {...this.props.home.homeMoreNews}]
        this.setState({
            dataSource: this.state.dataSource.cloneWithRows(data),
            isLoading: false,
            storiesList: data
        });
    }

    render() {
        const {themes, homeList, editors} = this.props.home
        const {top_stories, stories} = homeList
        const row = (rowData, sectionID, rowID) => {
            // console.log('rowData' + JSON.stringify(rowData))
            // console.log('sectionID' + JSON.stringify(sectionID))
            // console.log('rowID' + JSON.stringify(rowID))
            return (
                <div>
                    <div className="list-wrap">
                        <div className="list-date">{formatWeekDate(rowData.date)}</div>
                    </div>
                    {
                        rowData.stories ? rowData.stories.map(story => {
                            return <HomeList key={story.id} id={story.id}
                                      imgUrl={story.images && story.images[0] ? agentImageURL(story.images[0]) : ''}
                                      title={story.title}></HomeList>
                        }) : null
                    }
                </div>
            )
        }
        return (
            <div className="home-wrapper">
                <NavBar iconName="ellipsis"
                        mode="dark"
                        onLeftClick={this.onOpenChange}
                >首页</NavBar>
                <Drawer
                    className="my-drawer"
                    style={{minHeight: document.documentElement.clientHeight - 45}}
                    contentStyle={{color: '#A6A6A6', textAlign: 'center'}}
                    sidebar={<Sidebar themes={themes} history={this.props.history}
                                      getTheme={() => this.props.getTheme()}
                                      onOpenChange={() => this.onOpenChange()}></Sidebar>}
                    open={this.state.open}
                    onOpenChange={this.onOpenChange}
                >
                    {/*{JSON.stringify(top_stories)}*/}
                    {
                        // 轮播
                        top_stories && top_stories.length > 1 ? <Carousel
                            autoplay={true}
                            infinite
                            selectedIndex={1}
                            swipeSpeed={35}
                        >
                            {top_stories && top_stories.length > 1 ? top_stories.map((elem, index) => {
                                return (
                                    elem.id ?
                                        <Link key={index} to={`/newsDetail/${elem.id}`}>
                                            <div
                                                className="carousel-item-wrap"
                                                style={{'backgroundImage': 'url(' + agentImageURL(elem.image) + ')'}}
                                                key={index}
                                            >
                                                <p className="carousel-title">{elem.title}</p>
                                            </div>
                                        </Link>
                                        : <div
                                            className="carousel-item-wrap"
                                            style={{'backgroundImage': 'url(' + agentImageURL(elem.image) + ')'}}
                                            key={index}
                                        >
                                            <p className="carousel-title">{elem.title}</p>
                                        </div>
                                )
                            }) : '没有数据'
                            }
                        </Carousel> : (top_stories && top_stories.length === 1 ?
                            <div>
                                {top_stories && top_stories.length === 1 ? top_stories.map((elem, index) => {
                                    return (
                                        elem.id ?
                                            <Link key={index} to={`/newsDetail/${elem.id}`}>
                                                <div
                                                    className="carousel-item-wrap"
                                                    style={{'backgroundImage': 'url(' + elem.image + ')'}}
                                                    key={index}
                                                >
                                                    <p className="carousel-title">{elem.title}</p>
                                                </div>
                                            </Link>
                                            : <div
                                                className="carousel-item-wrap"
                                                style={{'backgroundImage': 'url(' + elem.image + ')'}}
                                                key={index}
                                            >
                                                <p className="carousel-title">{elem.title}</p>
                                            </div>
                                    )
                                }) : '没有数据'
                                }
                            </div>
                            : '')
                    }
                    <div className="list-wrap">
                        <div className="avatar-wrap">
                            {editors ? <span>主编</span> : ''}
                            {
                                editors ? editors.map((item, index) => {
                                    return (
                                        <i key={index} style={{'backgroundImage': 'url(' + agentImageURL(item.avatar) + ')'}}/>
                                    )
                                }) : ''
                            }
                        </div>
                        <div className="list-date">今日新闻</div>
                        {
                            stories ? stories.map(item => {
                                return (
                                    <HomeList key={item.id} id={item.id}
                                              imgUrl={item.images && item.images[0] ? agentImageURL(item.images[0]) : ''}
                                              title={item.title}></HomeList>
                                )
                            }) : ''
                        }
                    </div>
                    <ListView ref="lv"
                              className="scroll-list-wrap"
                              dataSource={this.state.dataSource}
                        // renderHeader={() => <span>header</span>}
                              renderFooter={() => (<div style={{padding: 10, textAlign: 'center'}}>
                                  {this.state.isLoading ? <Icon type="loading"/> : null}
                              </div>)}
                              renderRow={row}
                        // renderSeparator={separator}
                              pageSize={10}
                              useBodyScroll
                              onScroll={() => {
                                  console.log('scroll');
                              }}
                              scrollRenderAheadDistance={500}
                              scrollEventThrottle={200}
                              onEndReached={this.onEndReached}
                              onEndReachedThreshold={10}
                    />
                </Drawer>
            </div>
        );
    }
}

export default connect(mapStateToProps, mapDispatchTpProps)(HomeContainer)

HomeContainer.propTypes = {
    home: PropTypes.object,
    match: PropTypes.object.isRequired,
    location: PropTypes.object.isRequired
}